#include "resultwindow.h"
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QDate>
#include <QFile>
#include <QMessageBox>
#include <QtMath>

double ResultWindow::getLatestBmi() const {
    return bmi;
}

QVector<double> ResultWindow::loadHistoricalBmi() const {
    QVector<double> historicalBmi;
    QFile file(username + "_records.txt");
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream stream(&file);
        while (!stream.atEnd()) {
            QString line = stream.readLine();
            QStringList parts = line.split(",");
            if (parts.size() == 6) {
                historicalBmi.append(parts[5].toDouble());
            }
        }
        file.close();
    }
    return historicalBmi;
}

QVector<double> ResultWindow::predictFutureBmi(const QVector<double> &historicalBmi) const {
    QVector<double> predictions;
    if (historicalBmi.size() < 2) {
        // 数据不足时使用简单预测
        predictions.append(bmi);
        predictions.append(bmi * 0.99);
        predictions.append(bmi * 0.98);
        predictions.append(bmi * 0.97);
        predictions.append(bmi * 0.96);
        predictions.append(bmi * 0.95);
    } else {
        // 简单线性回归预测
        double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
        int n = historicalBmi.size();

        for (int i = 0; i < n; ++i) {
            sumX += i;
            sumY += historicalBmi[i];
            sumXY += i * historicalBmi[i];
            sumX2 += i * i;
        }

        double a = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
        double b = (sumY - a * sumX) / n;

        for (int i = n; i < n + 6; ++i) {
            predictions.append(a * i + b);
        }
    }
    return predictions;
}

void ResultWindow::showTrendPrediction() {
    QVector<double> historicalBmi = loadHistoricalBmi();
    QVector<double> futureBmi = predictFutureBmi(historicalBmi);

    QString trendText = "📈 您的BMI趋势预测 (未来6个月):\n\n";
    QDate currentDate = QDate::currentDate();

    for (int i = 0; i < futureBmi.size(); ++i) {
        QDate futureDate = currentDate.addMonths(i + 1);
        QString assessment;
        if (futureBmi[i] < 18.5) assessment = "偏瘦";
        else if (futureBmi[i] < 24) assessment = "正常";
        else if (futureBmi[i] < 28) assessment = "超重";
        else assessment = "肥胖";

        trendText += QString("%1: BMI %.1f (%2)\n")
                         .arg(futureDate.toString("yyyy-MM"))
                         .arg(futureBmi[i], 0, 'f', 1)
                         .arg(assessment);
    }

    QMessageBox::information(this, "BMI趋势预测", trendText);
}

ResultWindow::ResultWindow(double bmi, const QString &username, QWidget *parent) :
    QMainWindow(parent), bmi(bmi), username(username)
{
    setWindowTitle("✨ BMI计算结果 ✨");
    resize(600, 500);
    setStyleSheet("background-color: #f8f9fa;");

    QString assessment;
    if (bmi < 18.5) assessment = "偏瘦";
    else if (bmi < 24) assessment = "正常";
    else if (bmi < 28) assessment = "超重";
    else assessment = "肥胖";

    QLabel *titleLabel = new QLabel("📊 您的BMI结果", this);
    titleLabel->setStyleSheet(
        "font-size: 20pt; "
        "font-weight: bold; "
        "color: #6c757d; "
        "font-family: 'Microsoft YaHei';"
        );

    bmiLabel = new QLabel(QString("🧮 BMI值: %1").arg(bmi, 0, 'f', 2), this);
    bmiLabel->setStyleSheet(
        "font-size: 16pt; "
        "color: #495057;"
        );

    assessmentLabel = new QLabel(QString("🏥 健康评估: %1").arg(assessment), this);
    assessmentLabel->setStyleSheet(
        "font-size: 16pt; "
        "color: #495057;"
        );

    saveBtn = new QPushButton("💾 保存本次记录", this);
    saveBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #adb5bd;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #6c757d;"
        "}"
        );

    adviceBtn = new QPushButton("💡 提供针对性健康建议", this);
    adviceBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #4cc9f0;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #4895ef;"
        "}"
        );

    goalBtn = new QPushButton("🎯 设定理想BMI值", this);
    goalBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #4cc9f0;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #4895ef;"
        "}"
        );

    historyBtn = new QPushButton("📜 查看历史记录", this);
    historyBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #f72585;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #b5179e;"
        "}"
        );

    trendBtn = new QPushButton("🔮 预测BMI趋势", this);
    trendBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #7209b7;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #560bad;"
        "}"
        );

    connect(adviceBtn, &QPushButton::clicked, this, &ResultWindow::requestAdvice);
    connect(goalBtn, &QPushButton::clicked, [this]() {
        emit requestGoalSetting();
    });
    connect(historyBtn, &QPushButton::clicked, [this]() {
        emit requestHistory();
    });
    connect(trendBtn, &QPushButton::clicked, [this]() {
        showTrendPrediction();
    });

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(titleLabel);
    layout->addWidget(bmiLabel);
    layout->addWidget(assessmentLabel);
    layout->addWidget(saveBtn);
    layout->addWidget(adviceBtn);
    layout->addWidget(goalBtn);
    layout->addWidget(historyBtn);
    layout->addWidget(trendBtn);
    layout->addStretch();

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);
}
